<template>
  <div class="m-order-list">
    <w-table :columns="getColumns(index)" v-for="(item, index) in list" :key="index">
      <!-- 拼单规则和进度 -->
      <tr v-if="type == 1">
        <td class="list-hd clearfix" colspan="9">
          <p class="fl">拼单规则</p>
          <p class="fl">拼单进度</p>
          <p class="fl">拼单结果</p>
        </td>
      </tr>
      <tr v-if="type == 1">
        <td class="list-bd clearfix" colspan="9">
          <div class="fl">
            <p>拼单结束时间：<span v-if="item.fightGoodsEndTime">{{getTimeStr(item.fightGoodsEndTime)}}</span></p>
            <p>拼单发货量：{{item.crowdfundingCount}}件</p>
            <p>订单最低起货量：<span v-text="toString(item.goodsGsp, 1)"></span></p>
          </div>
          <div class="fl">
            <p>已拼单量：{{item.checkOutCount}}件</p>
            <p>颜色已订量：<span v-text="toString(item.goodsInventoryDetail, 0)"></span></p>
          </div>
          <div class="fl">
            <!-- 拼单结果列表 item.isAlready == 0 -->
            <div v-show="showResultContent(item)">
              <div>
                剩余
                <w-count-down-time class="text-m"
                  :start="item.curTime"
                  :target="new Date(item.fightGoodsEndTime.time + 1000 * 60 * 60 * 24 * 15)"
                  @on-timer="isOverTime" v-if="item.fightGoodsEndTime">
                </w-count-down-time>
                处理时间！
              </div>
              <p style="line-height: 50px;">剩余时间结束不处理，将会自动设置为拼单失败！</p>
              <div>
                <w-button type="main" @on-click="onSetFight(1, item.goodsRuleId, '确定设置拼单成功')">拼单成功</w-button>
                <w-button type="main" @on-click="onSetFight(-1, item.goodsRuleId, '确定设置拼单失败')">拼单失败</w-button>
              </div>
            </div>
            <!-- 拼单中图标 -->
            <img src="../../assets/12.png" v-show="item.isAlready == 0" class="fight">
            <!-- 拼单失败 -->
            <img src="../../assets/14.png" v-show="item.isAlready == -1" class="fight">
            <!-- 拼单成功图标 -->
            <img src="../../assets/13.png" v-show="item.isAlready == 1" class="fight">
          </div>
        </td>
      </tr>

      <!-- 商品列表（拼单商品和普通商品公用） -->
      <tr v-for="(order, index) in item.childOrderInfo" :key="index">
        <td class="goods w20" style="width: 20%;" v-if="order.goodsInfo">
          <table class="goods-info">
            <tr v-for="(info, infoIndex) in JSON.parse(order.goodsInfo)" :key="infoIndex">
              <td>
                <img v-lazy="info.goods_mainphoto_path">
                <p>{{info.goods_name}}</p>
              </td>
            </tr>
          </table>
        </td>
        <td class="goods w20" style="width: 20%;" v-else>
          <img v-lazy="order.goodsMainPhotoPath">
          <p>{{order.goodsName}}</p>
        </td>
        <td>{{order.orderId}}</td>
        <td class="time">
          <p>{{order.addTime}}</p>
        </td>
        <td class="c-high">￥{{order.totalPrice.toFixed(2)}}</td>
        <td class="name" :title="order.userName">{{order.userName}}</td>
        <!--  发货方  -->
        <td class="name">{{showConsignor(order.consignor)}}</td>
        <td class="c-main">{{orderStatus(order.orderStatus)}}</td>
        <td>{{order.paymentName}}</td>
        <td class="operate" :class="{ remind: order.remindDeliver == 1 }">
          <!-- 如果是代付款，展示修改价格 -->
          <button v-if="order.orderStatus == 10" @click="modifyPrice(order)">修改价格</button>
          <button @click="$router.push(`/order/${order.id}`)">查看订单</button>
          <button @click="$router.push(`/order/print/${order.id}`)">打印订单</button>
          <button v-if="showDelivery(order, item)" @click="onDeliver(order.orderId, order.id)">确认发货</button>
          <!-- 修改发货方 -->
          <button :class="{'no-update': order.paymentName == '浙江农商行'}" v-if="order.orderStatus == 20" @click="onShowConsignor(order.consignor, order.id, order.paymentName)">修改发货方</button>
        </td>
      </tr>

      <!-- 暂无数据 -->
      <tr v-if="!item.childOrderInfo || item.childOrderInfo.length == 0">
        <td colspan="8">暂无订单数据</td>
      </tr>
    </w-table>
    <!-- 确认发货 -->
    <w-panel-fixed-wrap v-model="showPanel" title="确认发货" class="m-deliver" @on-cancel="onCancel" @on-confirm="onConfirm(type)">
      <div class="form-horizontal">
        <w-form-group>
          <w-label class="col-sm-4" :must="false">订单编号：</w-label>
          <w-input class="col-sm-6" :value="orderCode" :disabled="true"></w-input>
        </w-form-group>
        <w-form-group>
          <w-label class="col-sm-4" :must="false">物流单号：</w-label>
          <w-input class="col-sm-6" v-model="shipCode" :validate="false"></w-input>
        </w-form-group>
        <w-form-group>
          <w-label class="col-sm-4" :must="false">备注：</w-label>
          <w-input type="textarea" v-model="storeSelfMsg" class="col-sm-6" :validate="false"></w-input>
        </w-form-group>
      </div>
    </w-panel-fixed-wrap>
    <!-- 修改价格 -->
    <w-panel-fixed-wrap v-model="showChangePricePanel" width="900px" title="修改订单总价" class="m-deliver" @on-cancel="onCancel" @on-confirm="confirmModifyPrice">
      <div class="form-horizontal">
        <w-form-group class="col-sm-6">
          <w-label class="col-sm-4" :must="false">原商品总价：</w-label>
          <w-input class="col-sm-4" :value="priceChanged.currentPrice" :disabled="true"></w-input>
        </w-form-group>
        <w-form-group class="col-sm-6">
          <w-label class="col-sm-4" :must="false">原运费总价：</w-label>
          <w-input class="col-sm-4" :value="priceChanged.shipPrice" :disabled="true"></w-input>
        </w-form-group>
        <w-form-group class="col-sm-6">
          <w-label class="col-sm-4" :must="false">商品减免价格：</w-label>
          <w-input class="col-sm-4" v-model="priceChanged.subtrahendPrice" :validate="false"></w-input><span class="price">元</span>
        </w-form-group>
        <w-form-group class="col-sm-6">
          <w-label class="col-sm-4" :must="false">改后运费价格：</w-label>
          <w-input class="col-sm-4" v-model="priceChanged.updateShipPrice" :validate="false"></w-input><span class="price">元</span>
        </w-form-group>
        <w-form-group class="col-sm-6">
          <w-label class="col-sm-4" :must="false">实际售出价：</w-label>
          <w-label :must="false">{{priceChanged.currentPrice}}+{{priceChanged.updateShipPrice}}-{{priceChanged.subtrahendPrice}}={{(parseFloat(priceChanged.currentPrice) + parseFloat(priceChanged.updateShipPrice)-priceChanged.subtrahendPrice).toFixed(2)}}</w-label><span class="price">元</span>
        </w-form-group>
      </div>
    </w-panel-fixed-wrap>
    <!-- 修改发货方 -->
    <w-panel-fixed-wrap v-model="showConsignorPanel" title="修改发货方" class="m-deliver m-deliver-consignor" @on-cancel="onCancel" @on-confirm="onUpdateConsignor">
      <div class="form-horizontal radio-list">
        <div class="radio-consignor">
          <w-radio label="1" name="consignor" v-model="consignorParams.consignor">商家发货</w-radio>
        </div>
        <div class="radio-consignor">
          <w-radio label="2" name="consignor" v-model="consignorParams.consignor">平台发货</w-radio>
        </div>
      </div>
    </w-panel-fixed-wrap>
  </div>
</template>

<script>
  // 导入获取订单详情列表
  import { apiOrder } from '../../common/api'

  // 导入工具类
  import { formatDate } from '../../common/util'

  // 配置订单状态
  const ORDER_STATUS = {
    0: '订单取消',
    10: '待付款',
    16: '货到付款',
    20: '待发货',
    21: '退款中',
    22: '退款审核中',
    25: '已退款',
    30: '待收货',
    40: '已收货',
    41: '退货申请中',
    42: '退货审核中',
    45: '退货完成',
    50: '已评价',
    60: '已结束',
    65: '订单不可评价'
  }

  export default {
    props: {
      list: {
        type: Array,
        default: () => { return [] }
      },
      type: [Number]
    },
    data() {
      return {
        // 表格头
        columns: [
          {title: '商品', width: '20%'},
          {title: '订单编号'},
          {title: '下单时间'},
          {title: '订单总价'},
          {title: '购物用户名'},
          {title: '发货方'},
          {title: '订单状态'},
          {title: '支付方式'},
          {title: '操作'}
        ],
        showPanel: false,
        // 待发货code码
        sendCode: 20,
        // 当前编辑的订单编号
        orderCode: '',
        // 订单id
        orderId: '',
        consignor: '', // 发货方
        showConsignorPanel: false, // 默认隐藏修改发货方的弹框
        consignorParams: {
          accessToken: '',
          orderId: '',
          consignor: ''
        }, // 发货方信息更改数据
        // 物流单号
        shipCode: '',
        // 备注信息
        storeSelfMsg: '',
        // 展示改价的弹框
        showChangePricePanel: false,
        // 价格改变的参数
        priceChanged: {
          accessToken: this.$store.getters.token,
          orderId: '',
          currentPrice: 0,
          subtrahendPrice: 0,
          shipPrice: 0,
          updateShipPrice: 0,
          goodsFactoryPrice: 0
        }
      }
    },
    methods: {
      /**
       * 显示发货发
       */
      showConsignor(val) {
        if (val == 1) {
          return '商家发货'
        } else {
          return '平台发货'
        }
      },
      /*
      * 确认修改发货方弹框
      */
      onShowConsignor(consignorVal, orderId, payName) {
        // 农商行不可更改发货方
        if (payName == '浙江农商行') {
          return
        }
        this.showConsignorPanel = true
        this.consignorParams = {
          'accessToken': this.$store.getters.token,
          'orderId': orderId,
          'consignor': consignorVal
        }
      },
      /**
       * 确认修改发货方操作
       */
      onUpdateConsignor() {
        apiOrder.apiAlterConsignor(this.consignorParams).then(data => {
          this.$toast('修改发货方成功')
          this.showConsignorPanel = false
          // 通知父级重新调用接口，获取订单列表
          this.$emit('refress-order')
        })
      },
      /**
       * 展示拼单结束的结果
       */
      showResultContent(item) {
        return item.isAlready == -2
      },

      /**
       * 拼单商品设置拼单成功与失败操作
       */
      onSetFight(isAlready, goodsRuleId, tip) {
        this.$modal({
          title: '提示',
          content: tip,
          onConfirm: () => {
            let params = {
              'accessToken': this.$store.getters.token,
              'goodsRuleId': goodsRuleId,
              'type': isAlready
            }
            apiOrder.apiControlCrowdFund(params).then(data => {
              // 点击的是拼单成功
              if (isAlready == 1) {
                this.$toast('已经将订单状态设置为成功', () => {
                  // 重新加载订单
                  this.$emit('refress-order', 1)
                })
                return
              }
              // 点击的是拼单失败
              this.$toast('已经将订单状态设置为失败', () => {
                // 重新加载订单
                this.$emit('refress-order', 1)
              })
            })
          }
        })
        console.log(isAlready)
      },
      /**
       * 展示立即发货
       */
      showDelivery(order, mainOrder) {
        // 如果是普通商品，则展示立即发货按钮
        // if (this.type != 1) {
        //   return true
        // }
        // 如果发货码不对
        if (order.orderStatus != this.sendCode) {
          return false
        }
        // 如果没有拼单结束时间，说明是普通商品，则直接展示立即发货
        if (!mainOrder.fightGoodsEndTime) {
          return true
        }
        // 如果订单拼单时间大于当前时间，也不展示立即发货按钮
        if (mainOrder.fightGoodsEndTime.time > new Date().getTime()) {
          return false
        }
        // 如果订单未完成，也不展示立即发货按钮
        if (mainOrder.isAlready != 1) {
          return false
        }
        return true
      },

      /**
       * 获取时间
       */
      getTimeStr(fightGoodsEndTime) {
        return formatDate(new Date(fightGoodsEndTime.time), 'yyyy-MM-dd hh:mm:ss')
      },

      /**
       * 是否超时
       *
       * @param { Object } fightGoodsEndTime 拼单时间
       */
      isOverTime(fightGoodsEndTime) {
        console.log('超时，自动设置拼单失败')
        // 刷新列表
        this.$emit('refresh')
        return fightGoodsEndTime.time < new Date().getTime()
      },

      /**
       * 确认发货
       *
       * @param  { Number } code 订单编号
       * @param  { Number } id   订单id
       */
      onDeliver(code, id) {
        // 展示弹框
        this.showPanel = true

        // 设置订单编码
        this.orderCode = code

        // 设置订单id
        this.orderId = id
      },

      // 弹出框确认
      onConfirm(type) {
        if (!this.shipCode) {
          this.$toast('请输入物流单号')
          return
        }

        // 请求接口
        apiOrder.comfireDelivery(this.orderId, this.shipCode, this.storeSelfMsg, this.$store.getters.token).then((data) => {
          this.$toast('确认发货成功')

          // 请求父级刷新页面
          this.$emit('refress-order', type)

          // 隐藏弹框
          this.showPanel = false

          // 清空输入的备注信息
          this.storeSelfMsg = ''
        })
      },

      // 弹出框取消
      onCancel() {
        // 清空输入的备注信息
        this.storeSelfMsg = ''
        this.showPanel = false
        this.showChangePricePanel = false
      },

      /**
       * 展示表头
       * @param  { Number } index 当前的索引
       */
      getColumns(index) {
        if (index == 0) {
          return this.columns
        }
        return []
      },

      /**
       * 将json字符串转换成需要的格式
       *
       * @params { String }  jsonStr  商品的sku的JSON字符串
       * @params { Number }  type     需要处理的类型
       */
      toString(json, type) {
        // 如果传入的json字符串是空，则不处理
        if (!json || json.length == 0) {
          return ''
        }

        // 返回的字符串
        let returnStr1 = ''
        let returnStr2 = ''

        // 遍历数据
        json.forEach((v) => {
          // 将所有的尺码的数量累加起来
          returnStr1 += `${v.specpropertyName}: ${v.specpropertyCrowdSum}件  `

          // 如果显示已拼单量
          if (type != 1) {
            returnStr2 += `${v.specpropertyName}: ${v.checkOutCount}件  `
          }
        })

        // 如果需要展示最低起货量
        if (type == 1) {
          return returnStr1
        }

        // 如果需要展示已拼量
        return returnStr2
      },

      /**
       * 获取订单状态
       */
      orderStatus(index) {
        return ORDER_STATUS[index]
      },

      /**
       * 修改价格
       *
       * @param { Object } order 订单
       */
      modifyPrice(order) {
        // 赋值订单id
        this.priceChanged.orderId = order.orderId

        // 赋值订单价格
        this.priceChanged.currentPrice = (order.goodsAmount || 0).toFixed(2)

        // 展示弹框
        this.showChangePricePanel = true

        // 赋值运费价格
        this.priceChanged.shipPrice = (order.originalShipPrice || order.shipPrice || 0).toFixed(2)

        // 修改后的运费价格
        this.priceChanged.updateShipPrice = (order.shipPrice || 0).toFixed(2)

        // 修改后的运费价格
        this.priceChanged.subtrahendPrice = (order.subtrahendPrice || 0).toFixed(2)

        // 赋值出厂价
        this.priceChanged.goodsFactoryPrice = JSON.parse(this.list[0].childOrderInfo[0].goodsInfo)[0].factoryPrice * JSON.parse(this.list[0].childOrderInfo[0].goodsInfo)[0].goodsTotalcount
      },

      /**
       * 确认修改价格
       */
      confirmModifyPrice() {
        if (!/^\d+(\.\d+)?$/.test(this.priceChanged.subtrahendPrice) && !/^\d+(\.\d+)?$/.test(this.priceChanged.updateShipPrice)) {
          this.$toast('价格只能由数字或数字和.组成')
          return
        }
        // 将价格格式化成数值
        this.priceChanged.subtrahendPrice = Number(this.priceChanged.subtrahendPrice)

        // 如果修改的商品减免价格小于0，则不让其提交
        if (this.priceChanged.subtrahendPrice < 0 || isNaN(this.priceChanged.subtrahendPrice)) {
          this.priceChanged.subtrahendPrice = 0
          this.$toast('请输入大于或等于0的商品减免价格')
          return
        }
        // 如果修改的运费价格小于0，则不让其提交
        if (this.priceChanged.updateShipPrice < 0 || isNaN(this.priceChanged.updateShipPrice)) {
          this.priceChanged.updateShipPrice = 0
          this.$toast('请输入大于或等于0的改后运费价格')
          return
        }
        // 如果修改的值等于，则不让其提交
        // if (this.priceChanged.subtrahendPrice == 0 && this.priceChanged.updateShipPrice == 0) {
        //   this.$toast('请至少修改一项')
        //   return
        // }
        // 如果修改的值小于出厂价，则不让其提交
        // if (((parseFloat(this.priceChanged.currentPrice) + parseFloat(this.priceChanged.updateShipPrice) - this.priceChanged.subtrahendPrice).toFixed(2)) <= this.priceChanged.goodsFactoryPrice) {
        //   this.$toast(`实际售出价需大于${this.priceChanged.goodsFactoryPrice}元出厂价`)
        //   return
        // }
        // 修改价格
        apiOrder.updatePrice(this.priceChanged).then((v) => {
          // 清空之前输入的价格
          this.priceChanged.subtrahendPrice = 0
          this.priceChanged.updateShipPrice = 0
          // 重新加载订单
          this.$emit('refress-order')

          // 展示弹框
          this.showChangePricePanel = false
        })
      }
    }
  }
</script>

<style lang="scss">
  .m-order-list {
    .m-deliver-consignor  {
      .m-panel-wrap {
        height: 200px !important;
      }
    }
  }
</style>

<style lang="scss" scoped>
  @import '../../scss/_var.scss';
  .goods-info {
    td {
      border: none
    }
  }
  .radio-consignor {
    display: inline-block;
    margin: 0 auto;
    width: 150px;
  }
  .radio-list {
    width: 310px;
    margin: 0 auto;
  }
  .no-update {
    color: $color-disabled !important;
  }
  .m-order-list {
    margin-top: 30px;
  }
  .text-m {
    color: $color-main
  }
  .w20 {
    width: 20%;
  }

  .price {
    display: inline-block;
    padding: 0px 6px;
    line-height: 20px;
  }

  .list-bd {
    overflow: inherit;
    position: relative;
  }
  .list-hd p {
    color: #666;
  }
  .m-order-list {
    .fl {
      width: 33%;
    }
  }

  .fight {
    height: 120px;
    width: 120px;
    position: absolute;
    top: 6px;
    // right: 40px;
    right: 23%
  }

  .operate {
    position: relative;

    &.remind {
      background: url('../../assets/remind.png') right top no-repeat;
    }
  }
  .name {
    max-width: 130px;
  }
</style>